package com.oc.claimobs.bb.screens;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Screen;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BasicEditField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.ObjectChoiceField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;

import com.oc.claimobs.bb.ScreenFlow;
import com.oc.claimobs.bb.facade.DiccionarioService;
import com.oc.claimobs.bb.facade.ReclamoService;
import com.oc.claimobs.bb.gps.LocationHelper;
import com.oc.claimobs.bb.model.Reclamo;
import com.oc.claimobs.bb.ui.TouchScreenFieldFocusChangeListener;
import com.oc.claimobs.data.Diccionario;
import com.oc.claimobs.data.TipoReclamos;
import com.oc.utils.Style;
import com.oc.utils.TextUtils;

public class DireccionScreen extends MainScreen {
	private Bitmap backgroundBitmap;

	public DireccionScreen() {
		super( MainScreen.NO_HORIZONTAL_SCROLL | MainScreen.NON_FOCUSABLE  | MainScreen.NO_HORIZONTAL_SCROLLBAR);
		init();
	}
	
	String[] calles; 
	//AutoCompleteField fld_calle;
	BasicEditField fld_calle;
	//LabelField log ;
    ObjectChoiceField fld_reclamo;
	ObjectChoiceField fld_calleList;
	BasicEditField fld_altura;
	String tipos[] = { "Ingrese la calle debajo...", "." };
	
	//
	String tiposDeReclamovalores[] = TipoReclamos.CODIGO;
	String tiposDeReclamo[] = TipoReclamos.TIPO;
	
	private void init() {

		// The background image.
		backgroundBitmap = Bitmap.getBitmapResource("img/title_back.png");

		VerticalFieldManager vfm = new VerticalFieldManager(
				VerticalFieldManager.NO_VERTICAL_SCROLL
						| VerticalFieldManager.NO_VERTICAL_SCROLLBAR
						| VerticalFieldManager.USE_ALL_WIDTH
						| VerticalFieldManager.NON_FOCUSABLE
						| VerticalFieldManager.USE_ALL_HEIGHT) {

			// Override the paint method to draw the background image.
			public void paint(Graphics graphics) {
				// Draw the background image and then call paint.
				graphics.drawBitmap(0, 0, Style.getScreenWidht(), 40, backgroundBitmap, 0, 0);
				super.paint(graphics);
			}
		};

		//Boton
		ButtonField button = new ButtonField("Siguiente", ButtonField.FOCUSABLE
						| ButtonField.RIGHT);
		button.setMargin(15,15,15,15);
		//button.setFocusListener(new TouchScreenButtonFocusChangeListener(this));
		button.setChangeListener(new FieldChangeListener() {
			public void fieldChanged(Field field, int context) {
				reset();
				if(validate())
				{
					sendNext("success");
				} 
			}
		});
		

		//Tipo reclamo
		LabelField lbl_reclamo = new LabelField("Tipo de Reclamo",Field.FIELD_LEFT | Field.NON_FOCUSABLE);
		lbl_reclamo.setMargin(60, 18, 0, 18);
		vfm.add(lbl_reclamo);

  
        fld_reclamo = new ObjectChoiceField("",tiposDeReclamo,1,Field.FIELD_LEFT);
        fld_reclamo.setMargin(15, 10, 0, 10);
        vfm.add(fld_reclamo);  
       
		
		//Calle
		LabelField lbl_calle = new LabelField("Calle",Field.FIELD_LEFT | Field.NON_FOCUSABLE);
		lbl_calle.setMargin(15, 18, 0, 18);
		vfm.add(lbl_calle);
		

		fld_calle = new BasicEditField("", "", 38, BasicEditField.NON_SPELLCHECKABLE |
				BasicEditField.NO_LEARNING |
				BasicEditField.NO_NEWLINE | BasicEditField.FILTER_DEFAULT);
		fld_calle.setMargin(5, 18, 0, 18);
		fld_calle.setBorder(Style.fieldBorder());
		fld_calle.setFocusListener(new TouchScreenFieldFocusChangeListener(this));

		fld_calle.setChangeListener(new FieldChangeListener() {
			public void fieldChanged(Field field, int context) {
				activarPredictivo(field);
				
				//UiApplication.getUiApplication().invokeLater(new Runnable() {
				//	public void run() {
				//		String s = fld_calle.getText();
				//		log.setText(s);
				//	}
				//});
			}
		});
		
		fld_calleList = new ObjectChoiceField("", tipos, 1, Field.FIELD_LEFT);
		fld_calleList.setMargin(15, 10, 0, 10);
		fld_calleList.setSelectedIndex(0);
		fld_calleList.setVisualState(ObjectChoiceField.VISUAL_STATE_DISABLED);
		fld_calleList.setChangeListener(new FieldChangeListener(){
			public void fieldChanged(Field arg0, int arg1) {
				if(fld_calleList.getSelectedIndex() > 0){
					fld_calle.setText(fld_calleList.toString());
			}
		}});
		
		//Invertidos...
		vfm.add(fld_calleList);
		vfm.add(fld_calle);
		
		//log = new LabelField("", Field.FIELD_LEFT | Field.NON_FOCUSABLE);
		//vfm.add(log);
		
		
		//fld_calle = new AutoCompleteField(lista);
		//fld_calle.setMargin(15, 10, 0, 10);
		//vfm.add(fld_calle);
		
		
		//Altura 
		LabelField lbl_altura = new LabelField("Altura", Field.FIELD_LEFT | Field.NON_FOCUSABLE);
		lbl_altura.setMargin(15, 18, 0, 18);
		vfm.add(lbl_altura);

		fld_altura = new BasicEditField("", "", 10, BasicEditField.NON_SPELLCHECKABLE |
				BasicEditField.NO_NEWLINE | Field.FIELD_LEFT | BasicEditField.FILTER_NUMERIC);
		fld_altura.setMargin(5, 200, 0, 18);
		fld_altura.setBorder(Style.fieldBorder());
		fld_altura.setFocusListener(new TouchScreenFieldFocusChangeListener(this));
		vfm.add(fld_altura);
		
	
        
    	//Boton
		ButtonField button2 = new ButtonField("Mis datos", ButtonField.CONSUME_CLICK
						| ButtonField.LEFT);
		button2.setMargin(15, 15, 15, 15);
		button2.setChangeListener(new FieldChangeListener() {
			public void fieldChanged(Field field, int context) {
				 sendNext("setup");
			}
		});
		
		HorizontalFieldManager hfm = new HorizontalFieldManager(
				HorizontalFieldManager.NO_VERTICAL_SCROLL | HorizontalFieldManager.NO_VERTICAL_SCROLLBAR |
				HorizontalFieldManager.NO_HORIZONTAL_SCROLL | HorizontalFieldManager.NO_HORIZONTAL_SCROLLBAR | 
				HorizontalFieldManager.USE_ALL_WIDTH| HorizontalFieldManager.NON_FOCUSABLE );
		hfm.setMargin(15,0,0,0);
		hfm.add(button2);
		hfm.add(button);

		vfm.add(hfm);

		// Add the manager to the screen.
		add(vfm);
	
		// Load data
		ReclamoService service = new ReclamoService();
		int i = ScreenFlow.getInstance().getCurrentSession();
		Integer k = new Integer(i);
		Reclamo o = service.getByKey(k);
		if (o != null) {
			try {
				fld_altura.setText(o.getAlturaCalle());
			
				//
				//fld_calle.getEditField().setText(o.getCalle());
				fld_calle.setText(o.getCalle());
				
				
				//
				String[] d = TextUtils.split(o.getReclamoTipo(), "|");
				int selectedIndex = TextUtils.findPos(d[1], tiposDeReclamovalores);
				fld_reclamo.setSelectedIndex(selectedIndex);
			} catch (Exception ex) {}
		}
	}
	
	
	
	
	public void activarPredictivo(Field field){
		String t = ((BasicEditField)field).getText();
		if(t.length() > 3){
			//TODO - Mejorar algoritmo de search.
			DiccionarioService service = new DiccionarioService();
			String[] choices = service.startsWith(t, Diccionario.CASE_INSENSITIVE);
			String[] options = new String[choices.length+1];
			if(choices.length == 0){
				options = tipos;
			} else {
				options[0] = "Quiso decir... (" + choices.length + " opciones)";
				System.arraycopy(choices,0, options, 1, choices.length);
			}
			fld_calleList.setChoices(options);
		} else {
			String tipos[] = { "Ingrese al menos 3 letras" };
			fld_calleList.setChoices(tipos);
		}
	}

	public void sendNext(String message){

		// Save
		ReclamoService service = new ReclamoService();
		int i = ScreenFlow.getInstance().getCurrentSession();
		Integer k = new Integer(i);
		Reclamo o = service.getByKey(k);
		if (o == null) {
			o = new Reclamo();
		}
		
		//String c = fld_calle.getEditField().getText();
		String c =  fld_calleList.toString() + "|" + fld_calle.getText();
		o.setCalle(c);
		o.setAlturaCalle(fld_altura.getText());
		
		String  tipotexto = fld_reclamo.toString();
		String valoretexto =  tiposDeReclamovalores[fld_reclamo.getSelectedIndex()];
		
		String d = tipotexto + "|" + valoretexto ;
		o.setReclamoTipo(d);
		
		String latlong = LocationHelper.getLatLong(ScreenFlow.getInstance().getCurrentLocation());
		o.setLatlong(latlong);
		service.saveOrUpdate(k, o);

		// Redirect
		Screen screen = ScreenFlow.getInstance().getNext(message);
		UiApplication.getUiApplication().pushScreen(screen);
		try {
			UiApplication.getUiApplication().popScreen(
					ScreenFlow.getInstance().getDIRECCION_PAGE());
		} catch (IllegalArgumentException e) {
		}
	}
	
	
	public void reset()
	{
		fld_calle.setBorder(Style.fieldBorder());
		fld_calle.selectionDelete();
		fld_altura.setBorder(Style.fieldBorder());
	}
	
	public boolean validate()
	{
		boolean b = true;
		//if(fld_calle.getSelectedObject() == null){
		//	fld_calle.getEditField().setBorder(Style.errorFieldBorder());
		//	b = false;
		//}
		if(fld_calle.getText().length() < 1){
			fld_calle.setBorder(Style.errorFieldBorder());
			b = false;
		}
		
		if(fld_altura.getText().length() < 1){
			fld_altura.setBorder(Style.errorFieldBorder());
			b = false;
		}
		
		if(!b){
			UiApplication.getUiApplication().invokeLater(new Runnable() {
				public void run() {
					Dialog.alert("Corrija los errores marcados en el formulario, e intente nuevamente");
				}
			});
		}
		
		return b;
	}

	public void close() {
		this.setDirty(false);
		super.close();
	}
	
	protected boolean invokeAction(int action) {
		boolean handled = super.invokeAction(action);

		if (!handled) {
			switch (action) {
				case ACTION_INVOKE: // Trackball click.
				{
					return true;
				}
			}
		}
		return handled;
	}

}
